package com.jinyi.wwdeng.ui.steps.act

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Environment
import android.view.Gravity
import android.view.View
import androidx.camera.core.AspectRatio
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.jinyi.base.network.NetworkUtils
import com.jinyi.base.utils.BarUtils
import com.jinyi.base.utils.img.ImageUtil
import com.jinyi.base.utils.log.HHLog
import com.jinyi.lib_http.callback.StringCallback
import com.jinyi.lib_http.model.Progress
import com.jinyi.lib_http.model.Response
import com.jinyi.lib_http.request.base.Request
import com.jinyi.wwdeng.App
import com.jinyi.wwdeng.R
import com.jinyi.wwdeng.databinding.ActOcrCameraFaceBinding
import com.jinyi.wwdeng.network.ApiService
import com.jinyi.wwdeng.pro.ProAct
import com.jinyi.wwdeng.ui.user.act.UserFeedbackAct
import com.jinyi.wwdeng.utils.event.TrackEventType
import com.jinyi.wwdeng.utils.event.TrackEventUtils
import id.zelory.compressor.Compressor
import id.zelory.compressor.constraint.destination
import id.zelory.compressor.constraint.quality
import id.zelory.compressor.constraint.resolution
import id.zelory.compressor.constraint.size
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * JinYiTest
 * @Author wwdeng
 * @CreateTime: 2024/4/23 14:49
 * @Annotation：人脸拍照
 */
class OcrCameraFaceAct: ProAct() {

    lateinit var binding: ActOcrCameraFaceBinding

    private lateinit var cameraExecutor: ExecutorService
    private var imageCapture: ImageCapture? = null

    private var outputFile: File? = null
    //压缩后的图片
    private var compressedImageFile: File? = null
    override fun getRootView(): View {
        binding = ActOcrCameraFaceBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        setTitleBarVisibility(View.VISIBLE)
        setTitleBarColor(ContextCompat.getColor(this, R.color.color_353535))
        setBackBtnRes(R.mipmap.pic_back_white_icon)
        setRightBtnRes(R.mipmap.pic_kefu_white_icon)
        setTextTitle(getString(R.string.identity_authentication))
        setTextTitleColor(ContextCompat.getColor(this, com.jinyi.lib_base.R.color.color_ffffff))
        setTextTitleGravity(Gravity.CENTER)
        BarUtils.setStatusBarLightMode(this, false)

        initCamera()
        showTakeView()
    }

    override fun initListener() {
        //客服
        rootViewBinding.ivFun.setOnClickListener {
            onIntent(UserFeedbackAct::class.java)
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_CUSTOMER,"FaceCamera Page")
        }
        //拍照
        binding.btnTakePhoto.setOnClickListener {
            takeFilePhoto()
        }
        //重拍
        binding.btnRemake.setOnClickListener {
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_STEP_FACE_REMAKE,"")
            //删除图片
            if (outputFile != null && outputFile!!.isFile){
                outputFile!!.delete()
            }
            val imageView = binding.cameraView.preImageView
            imageView.visibility = View.GONE
            showTakeView()
        }
        //使用
        binding.btnUse.setOnClickListener {
            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_STEP_FACE_USE_PHOTO,"")
            showLoading("",false,true)
            uploadImageAction()
        }
    }

    override fun initData() {
    }

    private fun initCamera(){
        binding.cameraView.maskView.setMaskColor(ContextCompat.getColor(this, R.color.color_353535))
        cameraExecutor = Executors.newSingleThreadExecutor()
        startCamera()
    }

    /**
     * 打开相机预览
     */
    private fun startCamera() {
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener(Runnable {
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
            val preview = Preview.Builder()
                .setTargetAspectRatio(AspectRatio.RATIO_16_9)
                .build()
                .also {
                    it.setSurfaceProvider(binding.cameraView.previewView.surfaceProvider)
                }
            imageCapture = ImageCapture.Builder().build()
            //打开前置摄像头
            val cameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA
            try {
                cameraProvider.unbindAll()
                cameraProvider.bindToLifecycle(this, cameraSelector, preview,imageCapture)
            } catch(exc: Exception) {
            }
        }, ContextCompat.getMainExecutor(this))
    }

    /**
     * 拍照并保存到本地
     */
    private fun takeFilePhoto(){
        if (imageCapture != null){
            //创建文件
//            val filePath = Environment.getExternalStorageDirectory().toString() + File.separator + "DCIM/Camera/";
            val filePath = App.instance().filesDir.absolutePath
            outputFile = File(filePath,"${System.currentTimeMillis()}.jpg")
            if (!outputFile!!.exists()){
                outputFile!!.mkdir()
            }
            //创建输出选项对象
            val metadata = ImageCapture.Metadata()
            metadata.isReversedHorizontal = true
            //创建文件
            val outputFileOptions = ImageCapture.OutputFileOptions.Builder(outputFile!!).setMetadata(metadata).build()
            //开始拍照
            imageCapture!!.takePicture(outputFileOptions,ContextCompat.getMainExecutor(this),object : ImageCapture.OnImageSavedCallback{
                override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                    val imgUri = outputFileResults.savedUri
                    //刷新图库
                    sendBroadcast(Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE", imgUri))

//                    Thread{
//                        binding.cameraView.crop(outputFile,outputFile,0)
//                    }.start()

                    HHLog.e("拍照成功>>>>>>>${imgUri!!.path}")
                    compressImage()

                    val imageView = binding.cameraView.preImageView
                    imageView.visibility = View.VISIBLE
                    ImageUtil.getInstance().loadImage(getContext(),imageView, imgUri.path)

                    showTakeCompleteView()
                }
                override fun onError(exception: ImageCaptureException) {
                    HHLog.e("拍照失败>>>>>>>${exception.message}")
                }
            })
        }
    }

    private fun compressImage() {
        outputFile?.let { imageFile ->
            lifecycleScope.launch {
                // Default compression
                compressedImageFile = Compressor.compress(this@OcrCameraFaceAct, imageFile) {
                    destination(outputFile!!)
                    resolution(1280, 720)
                    quality(80)
                    size(1_097_152) // 2 MB
                }
                setCompressedImage()
            }
        } ?: showToast("Please choose an image!")
    }

    private fun setCompressedImage() {
        compressedImageFile?.let {
            HHLog.e("压缩完成>>>>>>>>>>>"+it.absolutePath)
        }
    }

    /**
     * 显示拍照View
     */
    private fun showTakeView(){
        binding.btnTakePhoto.visibility = View.VISIBLE
        binding.completeLayout.visibility = View.GONE
    }

    /**
     * 显示拍照完成View
     */
    private fun showTakeCompleteView(){
        binding.btnTakePhoto.visibility = View.GONE
        binding.completeLayout.visibility = View.VISIBLE
    }

    //上传图片
    private fun uploadImageAction(){
        if (outputFile == null || !outputFile!!.isFile){
            hideLoading()
            return
        }
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.API_UPLOAD_FILE_URL)
        NetworkUtils.uploadFile(httpUrl,outputFile!!.absolutePath,object : StringCallback(){
            override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
                HHLog.e("正在上传中...")
            }

            override fun onSuccess(response: Response<String>?) {
                hideLoading()
                HHLog.e("上传完成："+response!!.body())
                if (response.code() == 200){
                    val data = JSONObject(response.body())
                    when(data.optInt("code")){
                        0 -> {//成功
                            val imgUrl = data.optJSONObject("obj")!!.optString("url")
                            val intent = intent
                            intent.putExtra("faceImgUrl",imgUrl)
                            intent.putExtra("faceImgPath",compressedImageFile!!.absolutePath)
                            setResult(RESULT_OK,intent)
                            finish()
                        }
                        else -> {
                            val msg = data.optString("msg")
                            showToast(msg)
                        }
                    }
                } else {
                    showToast(response.message())
                }
            }

            override fun onError(response: Response<String>?) {
                HHLog.e("上传出错"+response!!.body())
                showToast(response.message())
            }

            @SuppressLint("SetTextI18n")
            override fun uploadProgress(progress: Progress) {
                HHLog.e("正在上传中，uploadProgress: $progress")
                HHLog.e("正在上传中，文件总大小: ${progress.totalSize}")
                HHLog.e("正在上传中，当前进度: ${progress.currentSize}")
                val totalSize = progress.totalSize
                val currentSize = progress.currentSize
            }

            override fun onFinish() {
                hideLoading()
            }
        })
    }

    override fun onStart() {
        super.onStart()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_STEP_FACE_CAMERA_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        TrackEventUtils.logEvent(TrackEventType.PAGE.PAGE_STEP_FACE_CAMERA_END,"")
        cameraExecutor.shutdown()
    }
}